Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rustc pull update #2291

Merged
merged 18 commits into from
Apr 7, 2025
Merged

Rustc pull update #2291

merged 18 commits into from
Apr 7, 2025

Conversation

github-actions[bot]
Copy link

Latest update from rustc.

@rustbot rustbot closed this Mar 17, 2025
@rustbot rustbot reopened this Mar 17, 2025
@github-actions github-actions bot force-pushed the rustc-pull branch 3 times, most recently from 8276d2a to b0fe733 Compare March 27, 2025 04:02
@jieyouxu jieyouxu mentioned this pull request Apr 2, 2025
matthiaskrgr and others added 18 commits April 3, 2025 07:39
Experimental feature gate for `super let`

This adds an experimental feature gate, `#![feature(super_let)]`, for the `super let` experiment.

Tracking issue: rust-lang/rust#139076

Liaison: ``@nikomatsakis``

## Description

There's a rough (inaccurate) description here: https://blog.m-ou.se/super-let/

In short, `super let` allows you to define something that lives long enough to be borrowed by the tail expression of the block. For example:

```rust
let a = {
    super let b = temp();
    &b
};
```

Here, `b` is extended to live as long as `a`, similar to how in `let a = &temp();`, the temporary will be extended to live as long as `a`.

## Properties

During the temporary lifetimes work we did last year, we explored the properties of "super let" and concluded that the fundamental property should be that these two are always equivalent in any context:

1. `& $expr`
2. `{ super let a = & $expr; a }`

And, additionally, that these are equivalent in any context when `$expr` is a temporary (aka rvalue):

1. `& $expr`
2. `{ super let a = $expr; & a }`

This makes it possible to give a name to a temporary without affecting how temporary lifetimes work, such that a macro can transparently use a block in its expansion, without that having any effect on the outside.

## Implementing pin!() correctly

With `super let`, we can properly implement the `pin!()` macro without hacks: ✨

```rust
pub macro pin($value:expr $(,)?) {
    {
        super let mut pinned = $value;
        unsafe { $crate::pin::Pin::new_unchecked(&mut pinned) }
    }
}
```

This is important, as there is currently no way to express it without hacks in Rust 2021 and before (see [hacky definition](https://github.com/rust-lang/rust/blob/2a06022951893fe5b5384f8dbd75b4e6e3b5cee0/library/core/src/pin.rs#L1947)), and no way to express it at all in Rust 2024 (see [issue](rust-lang/rust#138718)).

## Fixing format_args!()

This will also allow us to express `format_args!()` in a way where one can assign the result to a variable, fixing a [long standing issue](rust-lang/rust#92698):

```rust
let f = format_args!("Hello {name}!"); // error today, but accepted in the future! (after separate FCP)
```

## Experiment

The precise definition of `super let`, what happens for `super let x;` (without initializer), and whether to accept `super let _ = _ else { .. }` are still open questions, to be answered by the experiment.

Furthermore, once we have a more complete understanding of the feature, we might be able to come up with a better syntax. (Which could be just a different keywords, or an entirely different way of naming temporaries that doesn't involve a block and a (super) let statement.)
Rustc dev guide subtree update

r? ``@jieyouxu`` ``@Kobzol``
… r=fmease

Fix the `f16`/`f128` feature gates on integer literals

The feature gating logic for `f16`/`f128` currently only checks float literals, meaning this code currently compiles with no feature gates on stable ([playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=b0c0e285ccb822fc7e2abc595557886b)):
```rust
fn main() {
    let a = 1f16;
    let b = 1f128;
    dbg!(a, b);
}
```
This PR fixes that.

Tracking issue: #116909
…tolnay

Make slice iterator constructors unstably const

See [tracking issue](rust-lang/rust#137737) for justification.

try-job: aarch64-apple
try-job: x86_64-gnu
compiletest: Require `//~` annotations even if `error-pattern` is specified

This is continuation of #138865 with some help from #139100.

`error-pattern` annotations that duplicate the newly added `//~` annotations are removed, other `error-pattern`s are not touched yet.

In exceptional cases `//@ compile-flags: --error-format=human` can be used to opt out of these checks.
In this PR I only had to use the opt out 3 times:
- `tests/ui/parser/utf16-{be,le}-without-bom.rs` - there are too many errors that are nearly identical (modulo location), because an error is reported on every second symbol
- `tests/ui-fulldeps/missing-rustc-driver-error.rs` - the errors list various rustc crate dependencies and may unexpectedly invalidate on random rustc changes
Rollup of 7 pull requests

Successful merges:

 - #139080 (Experimental feature gate for `super let`)
 - #139145 (slice: Remove some uses of unsafe in first/last chunk methods)
 - #139149 (unstable book: document import_trait_associated_functions)
 - #139273 (Apply requested API changes to `cell_update`)
 - #139282 (rustdoc: make settings checkboxes always square)
 - #139283 (Rustc dev guide subtree update)
 - #139294 (Fix the `f16`/`f128` feature gates on integer literals)

r? `@ghost`
`@rustbot` modify labels: rollup
gvn: Invalid dereferences for all non-local mutations

Fixes #132353.

This PR removes the computation value by traversing SSA locals through `for_each_assignment_mut`.

Because the `for_each_assignment_mut` traversal skips statements which have side effects, such as dereference assignments, the computation may be unsound. Instead of `for_each_assignment_mut`, we compute values by traversing in reverse postorder.

Because we compute and use the symbolic representation of values on the fly, I invalidate all old values when encountering a dereference assignment. The current approach does not prevent the optimization of a clone to a copy.

In the future, we may add an alias model, or dominance information for dereference assignments, or SSA form to help GVN.

r? cjgillot

cc `@jieyouxu` #132356
cc `@RalfJung` #133474
Initial support for auto traits with default bounds

This PR is part of ["MCP: Low level components for async drop"](rust-lang/compiler-team#727)
Tracking issue: #138781
Summary: rust-lang/rust#120706 (comment)

### Intro

Sometimes we want to use type system to express specific behavior and provide safety guarantees. This behavior can be specified by various "marker" traits. For example, we use `Send` and `Sync` to keep track of which types are thread safe. As the language develops, there are more problems that could be solved by adding new marker traits:

- to forbid types with an async destructor to be dropped in a synchronous context a trait like `SyncDrop` could be used [Async destructors, async genericity and completion futures](https://sabrinajewson.org/blog/async-drop).
- to support [scoped tasks](https://without.boats/blog/the-scoped-task-trilemma/) or in a more general sense to provide a [destruction guarantee](https://zetanumbers.github.io/book/myosotis.html) there is a desire among some users to see a `Leak` (or `Forget`) trait.
- Withoutboats in his [post](https://without.boats/blog/changing-the-rules-of-rust/) reflected on the use of `Move` trait instead of a `Pin`.

All the traits proposed above are supposed to be auto traits implemented for most types, and usually implemented automatically by compiler.

For backward compatibility these traits have to be added implicitly to all bound lists in old code (see below). Adding new default bounds involves many difficulties: many standard library interfaces may need to opt out of those default bounds, and therefore be infected with confusing `?Trait` syntax, migration to a new edition may contain backward compatibility holes, supporting new traits in the compiler can be quite difficult and so forth. Anyway, it's hard to evaluate the complexity until we try the system on a practice.

In this PR we introduce new optional lang items for traits that are added to all bound lists by default, similarly to existing `Sized`. The examples of such traits could be `Leak`, `Move`, `SyncDrop` or something else, it doesn't matter much right now (further I will call them `DefaultAutoTrait`'s). We want to land this change into rustc under an option, so it becomes available in bootstrap compiler. Then we'll be able to do standard library experiments with the aforementioned traits without adding hundreds of `#[cfg(not(bootstrap))]`s. Based on the experiments, we can come up with some scheme for the next edition, in which such bounds are added in a more targeted way, and not just everywhere.

Most of the implementation is basically a refactoring that replaces hardcoded uses of `Sized` with iterating over a list of traits including both `Sized` and the new traits when `-Zexperimental-default-bounds` is enabled (or just `Sized` as before, if the option is not enabled).

### Default bounds for old editions

All existing types, including generic parameters, are considered `Leak`/`Move`/`SyncDrop` and can be forgotten, moved or destroyed in generic contexts without specifying any bounds. New types that cannot be, for example, forgotten and do not implement `Leak` can be added at some point, and they should not be usable in such generic contexts in existing code.

To both maintain this property and keep backward compatibility with existing code, the new traits should be added as default bounds _everywhere_ in previous editions. Besides the implicit `Sized` bound contexts that includes supertrait lists and trait lists in trait objects (`dyn Trait1 + ... + TraitN`). Compiler should also generate implicit `DefaultAutoTrait` implementations for foreign types (`extern { type Foo; }`) because they are also currently usable in generic contexts without any bounds.

#### Supertraits

Adding the new traits as supertraits to all existing traits is potentially necessary, because, for example, using a `Self` param in a trait's associated item may be a breaking change otherwise:

```rust
trait Foo: Sized {
    fn new() -> Option<Self>; // ERROR: `Option` requires `DefaultAutoTrait`, but `Self` is not `DefaultAutoTrait`
}

// desugared `Option`
enum Option<T: DefaultAutoTrait + Sized> {
    Some(T),
    None,
}
```

However, default supertraits can significantly affect compiler performance. For example, if we know that `T: Trait`, the compiler would deduce that `T: DefaultAutoTrait`. It also implies proving `F: DefaultAutoTrait` for each field `F` of type `T` until an explicit impl is be provided.

If the standard library is not modified, then even traits like `Copy` or `Send` would get these supertraits.

In this PR for optimization purposes instead of adding default supertraits, bounds are added to the associated items:

```rust
// Default bounds are generated in the following way:
trait Trait {
   fn foo(&self) where Self: DefaultAutoTrait {}
}

// instead of this:
trait Trait: DefaultAutoTrait {
   fn foo(&self) {}
}
```

It is not always possible to do this optimization because of backward compatibility:

```rust
pub trait Trait<Rhs = Self> {}
pub trait Trait1 : Trait {} // ERROR: `Rhs` requires `DefaultAutoTrait`, but `Self` is not `DefaultAutoTrait`
```

or

```rust
trait Trait {
   type Type where Self: Sized;
}
trait Trait2<T> : Trait<Type = T> {} // ERROR: `???` requires `DefaultAutoTrait`, but `Self` is not `DefaultAutoTrait`
```

Therefore, `DefaultAutoTrait`'s are still being added to supertraits if the `Self` params or type bindings were found in the trait header.

#### Trait objects

Trait objects requires explicit `+ Trait` bound to implement corresponding trait which is not backward compatible:

```rust
fn use_trait_object(x: Box<dyn Trait>) {
   foo(x) // ERROR: `foo` requires `DefaultAutoTrait`, but `dyn Trait` is not `DefaultAutoTrait`
}

// implicit T: DefaultAutoTrait here
fn foo<T>(_: T) {}
```

So, for a trait object `dyn Trait` we should add an implicit bound `dyn Trait + DefaultAutoTrait` to make it usable, and allow relaxing it with a question mark syntax `dyn Trait + ?DefaultAutoTrait` when it's not necessary.

#### Foreign types

If compiler doesn't generate auto trait implementations for a foreign type, then it's a breaking change if the default bounds are added everywhere else:

```rust
// implicit T: DefaultAutoTrait here
fn foo<T: ?Sized>(_: &T) {}

extern "C" {
    type ExternTy;
}

fn forward_extern_ty(x: &ExternTy) {
    foo(x); // ERROR: `foo` requires `DefaultAutoTrait`, but `ExternTy` is not `DefaultAutoTrait`
}
```

We'll have to enable implicit `DefaultAutoTrait` implementations for foreign types at least for previous editions:

```rust
// implicit T: DefaultAutoTrait here
fn foo<T: ?Sized>(_: &T) {}

extern "C" {
    type ExternTy;
}

impl DefaultAutoTrait for ExternTy {} // implicit impl

fn forward_extern_ty(x: &ExternTy) {
    foo(x); // OK
}
```

### Unresolved questions

New default bounds affect all existing Rust code complicating an already complex type system.

- Proving an auto trait predicate requires recursively traversing the type and proving the predicate for it's fields. This leads to a significant performance regression. Measurements for the stage 2 compiler build show up to 3x regression.
    - We hope that fast path optimizations for well known traits could mitigate such regressions at least partially.
- New default bounds trigger some compiler bugs in both old and new trait solver.
- With new default bounds we encounter some trait solver cycle errors that break existing code.
    - We hope that these cases are bugs that can be addressed in the new trait solver.

Also migration to a new edition could be quite ugly and enormous, but that's actually what we want to solve. For other issues there's a chance that they could be solved by a new solver.
Folder experiment: Monomorphize region resolver

**NOTE:** This is one of a series of perf experiments that I've come up with while sick in bed. I'm assigning them to lqd b/c you're a good reviewer and you'll hopefully be awake when these experiments finish, lol.

r? lqd

This is actually two tweaks to the `RegionFolder`, monomorphizing its callback and accounting for flags to avoid folding unnecessarily.
…r_of_i686-pc-windows-gnu, r=workingjubilee

Demote i686-pc-windows-gnu to Tier 2

In accordance with [RFC 3771](rust-lang/rfcs#3771). FCP has been completed.

tracking issue #138422

I also added a stub doc page for the target and renamed the windows-gnullvm page for consistency.
…oli-obk

add `TypingMode::Borrowck`

Shares the first commit with #138499, doesn't really matter which PR to land first 😊 😁

Introduces `TypingMode::Borrowck` which unlike `TypingMode::Analysis`, uses the hidden type computed by HIR typeck as the initial value of opaques instead of an unconstrained infer var. This is a part of rust-lang/types-team#129.

Using this new `TypingMode` is unfortunately a breaking change for now, see tests/ui/impl-trait/non-defining-uses/as-projection-term.rs. Using an inference variable as the initial value results in non-defining uses in the defining scope. We therefore only enable it if with `-Znext-solver=globally` or `-Ztyping-mode-borrowck`

To do that the PR contains the following changes:
- `TypeckResults::concrete_opaque_type` are already mapped to the definition of the opaque type
  - writeback now checks that the non-lifetime parameters of the opaque are universal
  - for this, `fn check_opaque_type_parameter_valid` is moved from `rustc_borrowck` to `rustc_trait_selection`
- we add a new `query type_of_opaque_hir_typeck` which, using the same visitors as MIR typeck, attempts to merge the hidden types from HIR typeck from all defining scopes
  - done by adding a `DefiningScopeKind` flag to toggle between using borrowck and HIR typeck
  - the visitors stop checking that the MIR type matches the HIR type. This is trivial as the HIR type are now used as the initial hidden types of the opaque. This check is useful as a safeguard when not using `TypingMode::Borrowck`, but adding it to the new structure is annoying and it's not soundness critical, so I intend to not add it back.
- add a `TypingMode::Borrowck`  which behaves just like `TypingMode::Analysis` except when normalizing opaque types
   - it uses `type_of_opaque_hir_typeck(opaque)` as the initial value after replacing its regions with new inference vars
   - it uses structural lookup in the new solver

fixes #112201, fixes #132335, fixes #137751

r? `@compiler-errors` `@oli-obk`
hygiene: Avoid recursion in syntax context decoding

#139241 has two components
- Avoiding recursion during syntax context decoding
- Encoding/decoding only the non-redundant data, and recalculating the redundant data again during decoding

Both of these parts may influence compilation times, possibly in opposite directions.
So this PR contains only the first part to evaluate its effect in isolation.
Folder experiment: Micro-optimize RegionEraserVisitor

**NOTE:** This is one of a series of perf experiments that I've come up with while sick in bed. I'm assigning them to lqd b/c you're a good reviewer and you'll hopefully be awake when these experiments finish, lol.

r? lqd

The region eraser is very hot, so let's see if we can avoid erasing types (and visiting consts and preds that don't have region-ful types) unnecessarily.
Replace last `usize` -> `ptr` transmute in `alloc` with strict provenance API

This replaces the `usize -> ptr` transmute in `RawVecInner::new_in` with a strict provenance API (`NonNull::without_provenance`).

The API is changed to take an `Alignment` which encodes the non-null constraint needed for `Unique` and allows us to do the construction safely.

Two internal-only APIs were added to let us avoid UB-checking in this hot code: `Layout::alignment` to get the `Alignment` type directly rather than as a `usize`, and `Unique::from_non_null` to create `Unique` in const context without a transmute.
@jieyouxu jieyouxu enabled auto-merge April 7, 2025 04:36
@jieyouxu jieyouxu disabled auto-merge April 7, 2025 04:36
@jieyouxu jieyouxu closed this Apr 7, 2025
@jieyouxu jieyouxu reopened this Apr 7, 2025
@jieyouxu jieyouxu merged commit 5f6d843 into master Apr 7, 2025
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants